package com.dubbo.rpc.util;

import io.protostuff.LinkedBuffer;
import io.protostuff.ProtostuffIOUtil;
import io.protostuff.Schema;
import io.protostuff.runtime.RuntimeSchema;
import org.objenesis.Objenesis;
import org.objenesis.ObjenesisStd;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author liuxin
 * @date 2021/10/9 23:39
 */
public class SerializationUtil {

    private static final Map<Class<?>, Schema<?>> cacheSchema = new ConcurrentHashMap<>();

    private static final Objenesis objenesis = new ObjenesisStd(true);


    public static <T> byte[] serialize(T obj) {
        Class<T> cls = (Class<T>) obj.getClass();
        LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);

        try {
            Schema<T> schema = parseSchema(cls);
            return ProtostuffIOUtil.toByteArray(obj, schema, buffer);
        } catch (Exception e) {
            return null;
        } finally {
            buffer.clear();
        }
    }

    public static <T> T deserialize(byte[] data, Class<T> cls) {
        try {
            T message = objenesis.newInstance(cls);
            Schema<T> schema = parseSchema(cls);

            ProtostuffIOUtil.mergeFrom(data, message, schema);

            return message;
        } catch (Exception e) {
            return null;
        }
    }


    private static <T> Schema<T> parseSchema(Class<T> cls) {
        Schema<T> schema = (Schema<T>) cacheSchema.get(cls);
        if (Objects.isNull(schema)) {
            schema = RuntimeSchema.createFrom(cls);
            cacheSchema.put(cls, schema);
        }

        return schema;
    }

}
